package org.jeecg.modules.goods.rfqmanage.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.goods.rfqmanage.entity.RfqManage;
import org.jeecg.modules.goods.rfqmanage.service.IRfqManageService;
import org.jeecg.modules.goods.rfqmanage.dto.AuditRequestDto;
import org.jeecg.modules.goods.rfqmanagedetail.entity.RfqManageDetail;
import org.jeecg.modules.goods.rfqmanagedetail.service.IRfqManageDetailService;
import lombok.Data;
import io.swagger.v3.oas.annotations.media.Schema;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * @Description: 询报价主信息
 * @Author: jeecg-boot
 * @Date: 2025-06-07
 * @Version: V1.0
 */
@Slf4j
@Tag(name = "询报价主信息")
@RestController
@RequestMapping("/rfqmanage/rfqManage")
public class RfqManageController extends JeecgController<RfqManage, IRfqManageService> {

	/**
	 * 询报价主信息与明细信息DTO
	 */
	@Data
	@Schema(description="询报价主信息与明细信息DTO")
	public static class RfqManageWithDetailDto {
		/**询报价主信息*/
		@Schema(description = "询报价主信息")
		private RfqManage rfqManage;

		/**询报价明细信息列表*/
		@Schema(description = "询报价明细信息列表")
		private List<RfqManageDetail> rfqManageDetailList;
	}


	@Autowired
	private IRfqManageService rfqManageService;

	@Autowired
	private IRfqManageDetailService rfqManageDetailService;

	/**
	 * 分页列表查询
	 *
	 * @param rfqManage
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "询报价主信息-分页列表查询")
	@Operation(summary = "询报价主信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(RfqManage rfqManage,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			HttpServletRequest req) {
		QueryWrapper<RfqManage> queryWrapper = QueryGenerator.initQueryWrapper(rfqManage, req.getParameterMap());
		Page<RfqManage> page = new Page<RfqManage>(pageNo, pageSize);
		IPage<RfqManage> pageList = rfqManageService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 添加询报价主信息及明细信息
	 *
	 * @param rfqManageWithDetailDto
	 * @return
	 */
	@AutoLog(value = "询报价主信息-添加")
	@Operation(summary = "询报价主信息-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody RfqManageWithDetailDto rfqManageWithDetailDto) {
		try {
			RfqManage rfqManage = rfqManageWithDetailDto.getRfqManage();
			List<RfqManageDetail> rfqManageDetailList = rfqManageWithDetailDto.getRfqManageDetailList();

			// 新增时不应该有ID
			if (oConvertUtils.isNotEmpty(rfqManage.getId())) {
				return Result.error("新增操作不应包含ID");
			}

			boolean result = rfqManageService.saveOrUpdateWithDetail(rfqManage, rfqManageDetailList);

			if (result) {
				return Result.OK("添加成功！");
			} else {
				return Result.error("添加失败");
			}
		} catch (Exception e) {
			log.error("添加询报价信息失败", e);
			return Result.error("添加失败：" + e.getMessage());
		}
	}

	/**
	 * 修改询报价主信息及明细信息
	 *
	 * @param rfqManageWithDetailDto
	 * @return
	 */
	@AutoLog(value = "询报价主信息-修改")
	@Operation(summary = "询报价主信息-修改")
	@PutMapping(value = "/update")
	public Result<?> update(@RequestBody RfqManageWithDetailDto rfqManageWithDetailDto) {
		try {
			RfqManage rfqManage = rfqManageWithDetailDto.getRfqManage();
			List<RfqManageDetail> rfqManageDetailList = rfqManageWithDetailDto.getRfqManageDetailList();

			// 更新时必须有ID
			if (oConvertUtils.isEmpty(rfqManage.getId())) {
				return Result.error("更新操作必须包含ID");
			}

			boolean result = rfqManageService.saveOrUpdateWithDetail(rfqManage, rfqManageDetailList);

			if (result) {
				return Result.OK("修改成功！");
			} else {
				return Result.error("修改失败");
			}
		} catch (Exception e) {
			log.error("修改询报价信息失败", e);
			return Result.error("修改失败：" + e.getMessage());
		}
	}

	/**
	 * 编辑
	 *
	 * @param rfqManage
	 * @return
	 */
	@AutoLog(value = "询报价主信息-编辑")
	@Operation(summary = "询报价主信息-编辑")
	@RequestMapping(value = "/edit", method = { RequestMethod.PUT, RequestMethod.POST })
	public Result<?> edit(@RequestBody RfqManage rfqManage) {
		rfqManageService.updateById(rfqManage);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "询报价主信息-通过id删除")
	@Operation(summary = "询报价主信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		rfqManageService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "询报价主信息-批量删除")
	@Operation(summary = "询报价主信息-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		this.rfqManageService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "询报价主信息-通过id查询")
	@Operation(summary = "询报价主信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
		RfqManage rfqManage = rfqManageService.getById(id);
		return Result.OK(rfqManage);
	}

	/**
	 * 通过id查询询报价主信息及明细信息
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "询报价主信息-根据ID查询详情")
    @Operation(summary = "询报价主信息-根据ID查询详情")
    @GetMapping(value = "/queryWithDetailById")
    public Result<RfqManageWithDetailDto> queryWithDetailById(@RequestParam(name = "id", required = true) String id) {
        try {
            IRfqManageService.RfqManageWithDetailVo serviceResult = rfqManageService.queryWithDetailById(id);
            if (serviceResult == null) {
                return Result.error("未找到对应记录");
            }

            // 转换为DTO
            RfqManageWithDetailDto result = new RfqManageWithDetailDto();
            result.setRfqManage(serviceResult.getRfqManage());
            result.setRfqManageDetailList(serviceResult.getRfqManageDetailList());

            return Result.OK(result);
        } catch (Exception e) {
            log.error("查询询报价信息失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param rfqManage
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, RfqManage rfqManage) {
		return super.exportXls(request, rfqManage, RfqManage.class, "询报价管理");
	}

	/**
	 * 审核单据
	 *
	 * @param auditRequest 审核请求参数
	 * @return
	 */
	@PostMapping(value = "/audit")
	@Operation(summary="询报价管理-审核单据", description="询报价管理-审核单据")
	public Result<String> audit(@RequestBody AuditRequestDto auditRequest) {
		try {
			// 获取当前用户信息
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

			// 调用service层审核方法
			boolean success = rfqManageService.auditRfq(auditRequest, sysUser.getUsername());

			if (success) {
				String statusText = "1".equals(auditRequest.getAuditStatus()) ? "通过" : "不通过";
				return Result.OK("审核" + statusText + "成功");
			} else {
				return Result.error("审核失败");
			}

		} catch (IllegalArgumentException e) {
			return Result.error(e.getMessage());
		} catch (Exception e) {
			log.error("审核单据失败", e);
			return Result.error("审核失败：" + e.getMessage());
		}
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, RfqManage.class);
	}

}
